package com.drugmanage.exception;

import java.io.PrintWriter;
import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.drugmanage.constant.DmConstant;
import com.drugmanage.model.ResultInfo;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;


@Component
public class GlobalExceptionReslover implements HandlerExceptionResolver{

	@Override
	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		
		
		/**
		 * 1.视图
		 * 2.json
		 */
		if(handler instanceof HandlerMethod){
			
			if(ex instanceof NoLoginException) {
				NoLoginException ne=(NoLoginException) ex;
				ModelAndView modelAndView=getDefaultModelAndView(request);
				modelAndView.addObject("errorMsg", ne.getErrorMsg());
				return modelAndView;
			}
			
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			/**
			 * controller 响应的内容类型判断  view json
			 */
			
			Method method = handlerMethod.getMethod();
			ResponseBody responseBody = method.getAnnotation(ResponseBody.class);
			
			if(null!=responseBody){
				/**
				 * 响应为json
				 */
				ResultInfo resultInfo = new ResultInfo();
				resultInfo.setCode(DmConstant.OP_FAILED_CODE);
				resultInfo.setResult(DmConstant.OP_FAILED_MSG);
					if(ex instanceof ParamsExcetion){
						ParamsExcetion paramsException = (ParamsExcetion) ex;
						resultInfo.setCode(paramsException.getErrorCode());
						resultInfo.setMsg(paramsException.getErrorMsg());
					}
					response.setCharacterEncoding("UTF-8");
					response.setContentType("application/json;charset=utf-8");
					PrintWriter pw =null;
					try {
						pw = response.getWriter();
					} catch (Exception e) {
						e.printStackTrace();
					}finally{
						if(null!=pw){
							
							pw.write(JSON.toJSONString(resultInfo));
							pw.flush();
							pw.close();
						}
					}
					return null;
				
			}else{
				/**
				 * 响应的为视图
				 */
				ModelAndView mv = getDefaultModelAndView(request);
				if(ex instanceof ParamsExcetion){
					ParamsExcetion pe = (ParamsExcetion) ex;
					mv.addObject("errorMsg",pe.getErrorMsg());
				}
				return mv;
				
			}
			
		}
		return getDefaultModelAndView(request);
	}

	
	private ModelAndView getDefaultModelAndView(HttpServletRequest request) {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("error");
		mv.addObject("errorMsg", DmConstant.OP_FAILED_MSG);
		mv.addObject("ctx", request.getContextPath());
		mv.addObject("uri", request.getRequestURI());
		mv.addObject("errorMsg", "操作失败");
		return mv;
	}

}
